package com.pig4cloud.pigx.contract.api.v1.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.customize.api.enums.AbnormalEnum;
import com.pig4cloud.pigx.common.customize.api.util.OpenApiUtil;
import com.pig4cloud.pigx.contract.api.v1.service.FundingRateHistoryServiceV1;
import com.pig4cloud.pigx.contract.api.v1.utils.OpenApiContractUtilsV1;
import com.pig4cloud.pigx.contract.entity.RippleContractFundingRateHistory;
import com.pig4cloud.pigx.contract.mapper.RippleContractFundingRateHistoryMapper;
import com.pig4cloud.pigx.contract.mongo.entity.ContractSymbolMongo;
import com.pig4cloud.pigx.contract.open.api.vo.OpenApiFundingRateHistoryVOV1;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 */
@Service
@AllArgsConstructor
public class FundingRateHistoryServiceImplV1 extends ServiceImpl<RippleContractFundingRateHistoryMapper, RippleContractFundingRateHistory> implements FundingRateHistoryServiceV1 {

	private final OpenApiContractUtilsV1 apiContractUtils;

	@Override
	public R<List<OpenApiFundingRateHistoryVOV1>> getList(String symbolName) {
		// 币对校验
		ContractSymbolMongo mongo = apiContractUtils.getSymbolMongo(symbolName);
		try {
			List<RippleContractFundingRateHistory> histories = baseMapper.selectList(new QueryWrapper<RippleContractFundingRateHistory>() {{
				eq("symbol_id", mongo.getId());
				orderByDesc("date_time");
				last("limit 500");
			}});
			List<OpenApiFundingRateHistoryVOV1> list = new ArrayList<>();
			for (RippleContractFundingRateHistory history : histories) {
				OpenApiFundingRateHistoryVOV1 vo = new OpenApiFundingRateHistoryVOV1();
				BeanUtils.copyProperties(history, vo);
				vo.setSymbolName(mongo.getName());
				vo.setFundingRate(vo.getFundingRate().multiply(new BigDecimal(100)));
				list.add(vo);
			}
			return R.ok(list);
		} catch (Exception e) {
			throw OpenApiUtil.getError(AbnormalEnum.MSG.DISCONNECTED);
		}
	}

}
